package com.spring.vencent.container;

import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.spring.vencent.service.DBService;
import com.spring.vencent.service.LogService;

/**
 * 服务的提供场所
 * @author 1d
 *
 */
public class JNDIContainer {

	private Context ctx = null;  
	  
    public void init() throws Exception {  
        // 初始化JNDI提供者。  
        Hashtable<Object,Object> env = new Hashtable<Object,Object>();  
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");  
        env.put(Context.PROVIDER_URL, "file:/d:/works"); // fscontext的初始目录，我们需要在d:\下创建works目录。  
        ctx = new InitialContext(env);  
        loadServices();  
    }  
  
    // 从配置文件 JNDIContainer.properties中读取DBService和LogService实现，绑定到Context中。  
    private void loadServices() throws Exception {  
        InputStream in = getClass().getResourceAsStream("/JNDIContainer.properties");  
        Properties props = new Properties();  
        props.load(in);  
  
        // inject dbservice  
        String s = props.getProperty("DBServiceClass");  
        System.out.println("#" + s + "#");
        
        Object obj = Class.forName(s).newInstance();  
        if (obj instanceof DBService) {  
            DBService db = (DBService) obj;  
            String[] ss = props.getProperty("DBServiceProperty").split(";");  
            for (int i = 0; i < ss.length; i++)  
                db.setProperty(i, ss[i]);  
            ctx.rebind(props.getProperty("DBServiceName"), db);  
        }  
  
        // inject logservice  
        s = props.getProperty("LogServiceClass");  
        obj = Class.forName(s).newInstance();  
        if (obj instanceof LogService) {  
            LogService log = (LogService) obj;  
            ctx.rebind(props.getProperty("LogServiceName"), log);  
        }  
    }  
  
    public void close() throws NamingException {  
        ctx.close();  
    }  
  
    public Context getContext() {  
        return ctx;  
    }  
}
